package com.cmo.rzl.shine.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmo.rzl.core.dao.Db;
import com.cmo.rzl.core.jfinal.ext.kit.JsonKit;
import com.cmo.rzl.core.model.AjaxResult;
import com.cmo.rzl.core.toolbox.Record;
import com.cmo.rzl.shine.model.QueueType;
import com.cmo.rzl.shine.service.PatientQueueService;
import com.cmo.rzl.shine.service.QueueTypeService;
import com.cmo.rzl.shine.service.impl.PatientQueueServiceImpl;
import com.cmo.rzl.shine.service.impl.QueueTypeServiceImpl;
import com.cmo.rzl.system.controller.base.UrlPermissController;
import com.jfinal.kit.StrKit;

/**
 * Generated by Blade. 2017-08-03 10:50:24
 */
public class QueueTypeController extends UrlPermissController {
	private static String CODE = "queueType";
	private static String PERFIX = "queue_type";
	private static String LIST_SOURCE = "QueueType.list";
	private static String BASE_PATH = "/platform/queueType/";

	QueueTypeService service = new QueueTypeServiceImpl();
	PatientQueueService qservice = new PatientQueueServiceImpl();

	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "queueType.html");
	}

	public void add() {
		setAttr("code", CODE);
		// 查询分诊台列表,手动添加队列时,选定分诊台后不需要再分诊台下去分配队列
		// \u67E5\u8BE2\u5206\u8BCA\u53F0\u5217\u8868,\u624B\u52A8\u6DFB\u52A0\u961F\u5217\u65F6,\u9009\u5B9A\u5206\u8BCA\u53F0\u540E\u4E0D\u9700\u8981\u518D\u5206\u8BCA\u53F0\u4E0B\u53BB\u5206\u914D\u961F\u5217
		List<Record> list_triageName = service.queryTriageName();
		// 保存list
		// \u4FDD\u5B58list
		setAttr("list_triageName", list_triageName);
		render(BASE_PATH + "queueType_add.html");
	}

	public void edit() {
		String id = getPara(0);
		QueueType queueType = service.findById(id);
		setAttr("model", JsonKit.toJson(queueType));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "queueType_edit.html");
	}

	public void view() {
		String id = getPara(0);
		QueueType queueType = service.findById(id);
		setAttr("model", JsonKit.toJson(queueType));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "queueType_view.html");
	}

	public void list() {
		Object grid = paginate(LIST_SOURCE);
		renderJson(grid);
	}

	public void save() {
		QueueType queueType = mapping(PERFIX, QueueType.class);
		// 根据队列名称查询是否重复
		// \u6839\u636E\u961F\u5217\u540D\u79F0\u67E5\u8BE2\u662F\u5426\u91CD\u590D
		QueueType qt = service.queryQueueTypeName(queueType.getName());
		if (null != qt) {
			renderJson(error(QUEUE_TYPE_NAME_MSG));
			return;
		}
		queueType.setOpr_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss").format(new Date()));
		
		boolean temp = service.save(queueType);
		if (temp) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}

	public void update() {
		QueueType queueType = mapping(PERFIX, QueueType.class);
		boolean temp = service.update(queueType);
		if (temp) {
			String queue_type_id = queueType.getQueue_type_id().toString();
			QueueType qt = service.findById(queue_type_id);
			String oprtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
					.format(new Date());
			// 根据队列id查询患者列表
			List<Record> list = qservice.findpatientqueuetypeid(queue_type_id);
			String type = qt.getIs_checkin().toString();// 报道   
			if(list.size()>0){
				// 队列报道或不报道模式患者显示及隐藏
				boolean bool = qservice.updateisdisplay(
						Integer.parseInt(queue_type_id), type, oprtime);
				if (bool) {
					renderJson(success(UPDATE_SUCCESS_MSG));
				} else {
					renderJson(error(UPDATE_FAIL_MSG));
				}
			}
			// qt.getIs_reserve().toString();//预约
			String is_reorder= qt.getIs_reorder().toString();//重新排序
			if(list.size()>0){
				if(!"0".equals(is_reorder)){
					int i= qservice.deletepatientbyqueuetypeid(queue_type_id);
					if(i>0){
						renderJson(success(UPDATE_SUCCESS_MSG));
					}else {
						renderJson(error(UPDATE_FAIL_MSG));
					}
				}
			}
			// qt.getIs_pretriage().toString();//预分诊
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}

	public void select_queuetype() {
		int type = getParaToInt("type", 1);
		int aid = getParaToInt("aid", 0);

		String sql = "select queue_type_id,name,displayname from queue_type ";
		// 已选择
		if (type == 1) {
			sql += " where  triage_id=" + aid;
		} else {// 未选择
			sql += " where triage_id IS NULL ";
		}

		Object grid = paginate(sql);

		renderJson(grid);
	}

	public void updateChild() {

		int type = getParaToInt("type", 1);
		int aid = getParaToInt("aid");
		int gid = getParaToInt("gid");

		Record record = Record.create().set("aid", aid).set("gid", gid);
		AjaxResult result = new AjaxResult();

		result.setCode(0);
		if (type == 1) {

			String sql = "UPDATE queue_type set triage_id=#{aid} where queue_type_id =#{gid}";
			Db.init().update(sql, record);
			result.setMessage("添加成功");
		} else {
			String sql = "UPDATE queue_type set triage_id=NULL where queue_type_id =#{gid}";

			record.remove("aid");

			Db.init().update(sql, record);
			result.setMessage("移除成功");
		}
		renderJson(result);
	}

	public void select_pagerqueuetype() {
		int type = getParaToInt("type", 1);
		int aid = getParaToInt("aid", 0);
		System.out.println(aid);
		String sql="";
		// 已选择
		if (type == 1) {
			sql+="SELECT a.queue_type_id,a. NAME AS queuetypename FROM queue_type a "
					+ "INNER JOIN triage b ON a.triage_id = b.triage_id INNER JOIN pager c ON c.triage_id = b.triage_id INNER JOIN "
					+ "rlt_pager2queue_type d ON d.queue_type_id = a.queue_type_id AND d.pager_id = c.id WHERE c.id = "+aid+"";
		} else {// 未选择
			String sql1="SELECT a.queue_type_id FROM queue_type a "
					+ "INNER JOIN triage b ON a.triage_id = b.triage_id INNER JOIN pager c ON c.triage_id = b.triage_id INNER JOIN "
					+ "rlt_pager2queue_type d ON d.queue_type_id = a.queue_type_id AND d.pager_id = c.id WHERE c.id = "+aid+"";
			List<Record> list=Db.init().selectList(sql1);
			String str="";
			if(!list.isEmpty()){
				for(int i=0;i<list.size();i++){
					str+=list.get(i).get("queue_type_id").toString()+",";
				}
				str=str.substring(0,str.length()-1);
			}
			
			System.out.println(str+"*****************");
			sql += "SELECT a.queue_type_id, a. NAME AS queuetypename FROM queue_type a INNER JOIN triage b ON a.triage_id = b.triage_id "
					+ "INNER JOIN pager c ON c.triage_id = b.triage_id WHERE c.id = "+aid+"";
			if(!"".equals(str)){
				sql+=" AND a.queue_type_id NOT IN ("+str+")";
			}
		}

		Object grid = paginate(sql);

		renderJson(grid);
	}

	public void updatepagerChild() {

		int type = getParaToInt("type", 1);
		int aid = getParaToInt("aid");
		System.out.println(aid+"叫号器id*******************");
		int gid = getParaToInt("gid");
		System.out.println(gid+"队列id************************");

		Record record = Record.create().set("aid", aid).set("gid", gid);
		AjaxResult result = new AjaxResult();

		result.setCode(0);
		if (type == 1) {
			String sql = "INSERT INTO rlt_pager2queue_type VALUES("+aid+","+gid+",'111111',0)";
			Db.init().update(sql, record);
			result.setMessage("添加成功");
		} else {
			String sql = "DELETE FROM rlt_pager2queue_type WHERE pager_id="+aid+" AND queue_type_id="+gid+"";
			record.remove("aid");
			Db.init().update(sql, record);
			result.setMessage("移除成功");
		}
		renderJson(result);
	}

	public void save_queue() {
		Map<String, Object> map = new HashMap<String, Object>();
		String queuetype_strs = getPara("queuetypes");
		if (StrKit.isBlank(queuetype_strs)) {
			map.put("code", -1);
			map.put("msg", "请传值");
			renderJson(map);
			return;
		} else {
			JSONArray queuetypeList = JSONArray.parseArray(queuetype_strs);
			if (queuetypeList != null) {
				QueueType queuetype = null;
				for (Object json : queuetypeList) {
					JSONObject queuetype_json = (JSONObject) json;
					queuetype = new QueueType();
					QueueType qt = service.findBySource_id(queuetype_json
							.getString("source_id"));
					if (null != qt && qt.getSource_id() != null) {
						boolean bool = service
								.updateBy(
										"name='"
												+ queuetype_json
														.getString("name")
												+ "',displayname='"
												+ queuetype_json
														.getString("displayname")
												+ "'",
										" where source_id='"
												+ queuetype_json
														.getString("source_id")
												+ "'", null);
						if (bool) {
							map.put("code", 200);
							map.put("msg", "队列信息修改成功");
							renderJson(map);
						}
						return;
					} else {
						queuetype.setSource_id(queuetype_json
								.getString("source_id"));
						queuetype.setName(queuetype_json.getString("name"));
						queuetype.setDisplayname(queuetype_json
								.getString("displayname"));
						queuetype.setIs_checkin(2);
						queuetype.setIs_reorder(2);
						queuetype.setIs_pretriage(2);
						queuetype.setIs_reserve(2);
						boolean bool = service.save(queuetype);
						if (bool) {
							map.put("code", 200);
							map.put("msg", "成功");
							renderJson(map);
						} else {
							map.put("code", -1);
							map.put("msg", "失败");
							renderJson(map);
							return;
						}
					}
				}
			}
		}
		renderJson(map);
	}
}
